<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Db;
use think\Session;
use app\admin\model\AdminUser;
use app\admin\model\Role;
use app\admin\model\Permission;
use app\admin\model\UserRole;
use app\admin\model\RolePermission;
use app\admin\service\OperationLogService;

/**
 * 管理员、角色、权限管理控制器
 * Class Admin
 * @package app\admin\controller
 */
class Admin extends BaseController
{
    /**
     * 管理员列表
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $keyword = $this->request->param('keyword', '');
            
            $where = ['is_deleted' => 0];
            if (!empty($keyword)) {
                $where['username|real_name|phone'] = ['like', "%{$keyword}%"];
            }
            
            $list = AdminUser::where($where)
                ->page($page, $limit)
                ->order('id desc')
                ->select();
            
            $count = AdminUser::where($where)->count();
            
            // 获取用户角色
            foreach ($list as &$user) {
                $roleIds = UserRole::where('user_id', $user['id'])->column('role_id');
                $user['roles'] = Role::whereIn('id', $roleIds)->select();
            }
            
            return json(['code' => 0, 'msg' => '', 'count' => $count, 'data' => $list]);
        }
        
        return view();
    }
    
    /**
     * 添加管理员
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            
            // 验证必填字段
            if (empty($data['username']) || empty($data['password'])) {
                return json(['code' => 1, 'msg' => '用户名和密码不能为空']);
            }
            
            // 检查用户名是否已存在
            if (AdminUser::where('username', $data['username'])->find()) {
                return json(['code' => 1, 'msg' => '用户名已存在']);
            }
            
            // 添加管理员
            $admin = new AdminUser;
            $admin->username = $data['username'];
            $admin->password = md5($data['password']);
            $admin->real_name = $data['real_name'] ?? '';
            $admin->phone = $data['phone'] ?? '';
            $admin->email = $data['email'] ?? '';
            $admin->department = $data['department'] ?? '';
            $admin->position = $data['position'] ?? '';
            $admin->status = $data['status'] ?? 1;
            
            if ($admin->save()) {
                // 分配角色
                if (!empty($data['role_ids'])) {
                    $roleIds = is_array($data['role_ids']) ? $data['role_ids'] : explode(',', $data['role_ids']);
                    foreach ($roleIds as $roleId) {
                        $userRole = new UserRole;
                        $userRole->user_id = $admin->id;
                        $userRole->role_id = $roleId;
                        $userRole->save();
                    }
                }
                
                // 记录日志
                OperationLogService::log('添加管理员', 'admin', "添加管理员：{$admin->username}", ['admin_id' => $admin->id]);
                
                return json(['code' => 0, 'msg' => '添加成功']);
            }
            
            return json(['code' => 1, 'msg' => '添加失败']);
        }
        
        // 获取所有角色
        $roles = Role::where('status', 1)->select();
        $this->assign('roles', $roles);
        
        return view();
    }
    
    /**
     * 编辑管理员
     */
    public function edit()
    {
        $id = $this->request->param('id', 0);
        $admin = AdminUser::where('id', $id)->where('is_deleted', 0)->find();
        
        if (!$admin) {
            return json(['code' => 1, 'msg' => '管理员不存在或已被删除']);
        }
        
        if ($this->request->isPost()) {
            $data = $this->request->param();
            
            try {
                // 更新基本信息
                if (isset($data['real_name'])) $admin->real_name = $data['real_name'];
                if (isset($data['phone'])) $admin->phone = $data['phone'];
                if (isset($data['email'])) $admin->email = $data['email'];
                if (isset($data['department'])) $admin->department = $data['department'];
                if (isset($data['position'])) $admin->position = $data['position'];
                if (isset($data['status'])) $admin->status = $data['status'];
                
                // 如果提供了新密码，则更新密码
                if (!empty($data['password'])) {
                    $admin->password = md5($data['password']);
                }
                
                // 强制保存管理员信息（即使数据没有变化）
                $admin->force(true)->save();
                
                // 更新角色
                if (isset($data['role_ids'])) {
                    // 删除旧角色
                    UserRole::where('user_id', $id)->delete();
                    
                    // 分配新角色
                    $roleIds = is_array($data['role_ids']) ? $data['role_ids'] : explode(',', $data['role_ids']);
                    foreach ($roleIds as $roleId) {
                        if (!empty($roleId)) {
                            $userRole = new UserRole;
                            $userRole->user_id = $id;
                            $userRole->role_id = $roleId;
                            $userRole->save();
                        }
                    }
                }
                
                // 记录日志
                try {
                    OperationLogService::log('编辑管理员', 'admin', "编辑管理员：{$admin->username}", ['admin_id' => $id]);
                } catch (\Exception $e) {
                    // 日志失败不影响主流程
                }
                
                return json(['code' => 0, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '更新失败：' . $e->getMessage()]);
            }
        }
        
        // 获取所有角色
        $roles = Role::where('status', 1)->select();
        
        // 获取用户已分配的角色
        $userRoleIds = UserRole::where('user_id', $id)->column('role_id');
        
        $this->assign('admin', $admin);
        $this->assign('roles', $roles);
        $this->assign('userRoleIds', $userRoleIds);
        
        return view();
    }
    
    /**
     * 删除管理员
     */
    public function delete()
    {
        $id = $this->request->param('id', 0);
        
        if ($id == 1) {
            return json(['code' => 1, 'msg' => '不能删除超级管理员']);
        }
        
        $admin = AdminUser::where('id', $id)->where('is_deleted', 0)->find();
        if (!$admin) {
            return json(['code' => 1, 'msg' => '管理员不存在或已被删除']);
        }
        
        // 软删除
        $admin->is_deleted = 1;
        if ($admin->save()) {
            // 删除用户角色关联
            UserRole::where('user_id', $id)->delete();
            // 记录日志
            OperationLogService::log('删除管理员', 'admin', "删除管理员：{$admin->username}", ['admin_id' => $id]);
            return json(['code' => 0, 'msg' => '删除成功']);
        }
        
        return json(['code' => 1, 'msg' => '删除失败']);
    }
    
    /**
     * 角色列表
     */
    public function roles()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            
            $list = Role::page($page, $limit)->order('sort_order asc')->select();
            $count = Role::count();
            
            // 获取每个角色的权限数量
            foreach ($list as &$role) {
                $role['permission_count'] = RolePermission::where('role_id', $role['id'])->count();
            }
            
            return json(['code' => 0, 'msg' => '', 'count' => $count, 'data' => $list]);
        }
        
        return view();
    }
    
    /**
     * 添加角色
     */
    public function addRole()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            
            if (empty($data['role_name']) || empty($data['role_code'])) {
                return json(['code' => 1, 'msg' => '角色名称和代码不能为空']);
            }
            
            // 检查角色代码是否已存在
            if (Role::where('role_code', $data['role_code'])->find()) {
                return json(['code' => 1, 'msg' => '角色代码已存在']);
            }
            
            $role = new Role;
            $role->role_name = $data['role_name'];
            $role->role_code = $data['role_code'];
            $role->description = $data['description'] ?? '';
            $role->status = $data['status'] ?? 1;
            $role->sort_order = $data['sort_order'] ?? 0;
            
            if ($role->save()) {
                // 记录日志
                OperationLogService::log('添加角色', 'role', "添加角色：{$role->role_name}", ['role_id' => $role->id]);
                return json(['code' => 0, 'msg' => '添加成功']);
            }
            
            return json(['code' => 1, 'msg' => '添加失败']);
        }
        
        return view();
    }
    
    /**
     * 编辑角色
     */
    public function editRole()
    {
        $id = $this->request->param('id', 0);
        $role = Role::find($id);
        
        if (!$role) {
            return json(['code' => 1, 'msg' => '角色不存在']);
        }
        
        if ($this->request->isPost()) {
            $data = $this->request->param();
            
            $role->role_name = $data['role_name'] ?? $role->role_name;
            $role->description = $data['description'] ?? $role->description;
            $role->status = $data['status'] ?? $role->status;
            $role->sort_order = $data['sort_order'] ?? $role->sort_order;
            
            if ($role->save()) {
                // 记录日志
                OperationLogService::log('编辑角色', 'role', "编辑角色：{$role->role_name}", ['role_id' => $id]);
                return json(['code' => 0, 'msg' => '更新成功']);
            }
            
            return json(['code' => 1, 'msg' => '更新失败']);
        }
        
        $this->assign('role', $role);
        return view();
    }
    
    /**
     * 删除角色
     */
    public function deleteRole()
    {
        $id = $this->request->param('id', 0);
        
        if ($id == 1) {
            return json(['code' => 1, 'msg' => '不能删除超级管理员角色']);
        }
        
        $role = Role::find($id);
        if (!$role) {
            return json(['code' => 1, 'msg' => '角色不存在']);
        }
        
        // 检查是否有用户使用此角色
        $userCount = UserRole::where('role_id', $id)->count();
        if ($userCount > 0) {
            return json(['code' => 1, 'msg' => '该角色下还有用户，不能删除']);
        }
        
        if ($role->delete()) {
            // 删除角色权限关联
            RolePermission::where('role_id', $id)->delete();
            // 记录日志
            OperationLogService::log('删除角色', 'role', "删除角色：{$role->role_name}", ['role_id' => $id]);
            return json(['code' => 0, 'msg' => '删除成功']);
        }
        
        return json(['code' => 1, 'msg' => '删除失败']);
    }
    
    /**
     * 权限列表
     */
    public function permissions()
    {
        if ($this->request->isAjax()) {
            $list = Permission::order('sort_order asc')->select();
            return json(['code' => 0, 'msg' => '', 'count' => count($list), 'data' => $list]);
        }
        
        return view();
    }
    
    /**
     * 分配角色权限
     */
    public function assignPermissions()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 1, 'msg' => '请求方式错误']);
        }
        
        $roleId = $this->request->param('role_id/d', 0);
        // 使用 /a 修饰符强制获取数组类型，如果不是数组则返回空数组
        $permissionIds = $this->request->param('permission_ids/a', []);
        
        // 检查是否传入了数据
        if (empty($roleId)) {
            return json(['code' => 200, 'msg' => '保存成功', 'message' => '保存成功']);
        }
        
        $role = Role::find($roleId);
        if (!$role) {
            return json(['code' => 1, 'msg' => '角色不存在', 'message' => '角色不存在']);
        }
        
        try {
            // 处理权限ID数组
            if (!is_array($permissionIds)) {
                if (is_string($permissionIds)) {
                    $permissionIds = $permissionIds ? explode(',', $permissionIds) : [];
                } else {
                    $permissionIds = [];
                }
            }
            $permissionIds = array_filter($permissionIds); // 过滤空值
            
            // 删除旧权限
            RolePermission::where('role_id', $roleId)->delete();
            
            // 添加新权限
            if (!empty($permissionIds)) {
                foreach ($permissionIds as $permissionId) {
                    if (!empty($permissionId)) {
                        $rolePermission = new RolePermission;
                        $rolePermission->role_id = $roleId;
                        $rolePermission->permission_id = (int)$permissionId;
                        $rolePermission->save();
                    }
                }
            }
            
            // 记录日志
            try {
                OperationLogService::log('分配权限', 'role', "为角色 {$role->role_name} 分配权限", ['role_id' => $roleId]);
            } catch (\Exception $e) {
                // 日志失败不影响主流程
            }
            
            return json(['code' => 0, 'msg' => '权限分配成功', 'message' => '权限分配成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '权限分配失败：' . $e->getMessage(), 'message' => '权限分配失败：' . $e->getMessage()]);
        }
    }
}
